package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户注册
 */
@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        int data=0;
        String msg="未知错误";
        //1.从前端获取的参数
        String nickname = req.getParameter("nickname");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if(!StrUtil.isBlank(nickname) && !StrUtil.isBlank(username) && !StrUtil.isBlank(password)){
            //2.1将数据保存到数据库
            Connection connection= DBUtils.getConnection();

            //2.2 先判断用户名的唯一性
            String selSql="select * from userinfo where username=?";
            //2.3 得到执行器,执行执行器
            PreparedStatement statement = connection.prepareStatement(selSql);
            statement.setString(1,username);
            ResultSet result = statement.executeQuery();
            if(result.next()){
                //当前用户名已存在
                msg="您插入的登录名已存在，请更换登录名再试";
            }else{
                String sql="insert into userinfo(username,password,nickname) values(?,?,?)";
                statement = connection.prepareStatement(sql);
                statement.setString(1,username);
                statement.setString(2, SecureUtil.md5(password));
                statement.setString(3,nickname);
                data = statement.executeUpdate();
            }

            DBUtils.close(null,statement,connection);
        }else{
            msg="非法参数";
        }
        //3.将数据库返回的结果返回给前端
        resp.getWriter().println(JSONUtil.toJsonStr(
                ResultUtils.toResult(200, data, msg)));
    }
}
